import pandas as pd
import math
import matplotlib.pyplot as plt
import numpy as np


def addtodict2(thedict, key_a, key_b, val):
    if key_a in thedict:
        thedict[key_a].update({key_b: val * 0.1})

    else:
        thedict.update({key_a: {key_b: val * 0.1}})


def addtodict1(thedict, key, val):
    if key in thedict:
        thedict[key] += val * 0.1

    else:
        thedict[key] = val * 0.1


def printbook(item, book):
    itembook = []  # 索引存放的书的详情及推荐度
    items = {}  # 将item转为字典
    print(item)
    for i in item:
        itembook.append(book.loc[i[0]].tolist())
        items[i[0]] = i[1]
    x = []
    y = []
    for i in itembook:
        print(i)
        x.append(i[1])
        y.append(items[i[0]])
    index = np.arange(len(y))
    # 支持中文
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    # 绘制柱状图,
    plt.bar(index, y, 0.8)
    # 设置横轴标签
    plt.xlabel('书名')
    # 设置纵轴标签
    plt.ylabel('相似度')
    # 添加标题
    plt.title('书籍相似度')
    # 添加纵横轴的刻度
    plt.xticks(index, x)
    plt.xticks(size='small', rotation=8, fontsize=8)
    plt.show()
    print(y)


# 读入数据
books = pd.read_excel('../MyFile/MyBooks.xlsx')
ratings = pd.read_excel('../MyFile/MyRatings.xlsx')
books = books[['ISBN', 'bookTitle', 'bookAuthor']]
books.index = books['ISBN']

data = {}
NumBook1 = {}  # 喜欢书籍i的总评分
NumBook2 = {}  # 喜欢书籍i也喜欢书籍j的人数

# 求构建用户–>物品的倒排
# 列表示物品，值表示用户喜欢的程度
for index, row in ratings.iterrows():
    user = row['userID']
    item = row['ISBN']
    rating = row['bookRating']
    addtodict2(data, key_a=user, key_b=item, val=rating)
    addtodict1(NumBook1, key=item, val=rating)

# 加入每一本书的总评分并排序
books['rating'] = None
for i in NumBook1:
    books.loc[i, 'rating'] = NumBook1[i]
books = books.sort_values(by='rating', ascending=False)

# 构建物品与物品的同现矩阵
for user, item in data.items():
    for i, score in item.items():
        NumBook2.setdefault(i, {})
        for j, scores in item.items():
            if j not in i:
                NumBook2[i].setdefault(j, 0)
                NumBook2[i][j] += 1

similarBook = {}

# 计算相似矩阵
for i, item in NumBook2.items():
    similarBook.setdefault(i, {})
    for j, item2 in item.items():
        similarBook[i].setdefault(j, 0)
        similarBook[i][j] = NumBook2[i][j] / math.sqrt(NumBook1[i] * NumBook1[j])


# 测试
uid = ['The Bean Trees|1.0',"The Pilot's Wife : A Novel|0.9",'Me Talk Pretty One Day|0.9']
user = {}

# 找到用户书籍的ISBN
for i in uid:
    user_rating = i.split("|")
    for index, row in books.iterrows():
        if row['bookTitle'] == user_rating[0]:
            user[row['ISBN']] = user_rating[1]
            break


'''
for i in uid:
    user_rating = i.split("|")
    user[user_rating[0]]=user_rating[1]
'''

rank = {}
for i in user:
    tool = similarBook[i]
    tool2 = sorted(tool.items(), key=lambda d: d[1], reverse=True)
    for j, w in tool2[0:10]:  # 获得与物品i相似的k个物品
        if j not in user.keys():  # 该相似的物品不在用户user的记录里
            rank.setdefault(j, 0)
            rank[j] += float(user[i]) * w

# 选取排名前十的书籍
rank2 = sorted(rank.items(), key=lambda d: d[1], reverse=True)[0:10]
printbook(rank2, books)
